package com.ctgu.AutoIdentify.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.ctgu.AutoIdentify.DTO.PredictDTO;
import com.ctgu.AutoIdentify.entity.Record;
import com.ctgu.AutoIdentify.mapper.RecordMapper;
import com.ctgu.AutoIdentify.service.IRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements IRecordService {

    @Autowired
    private RestTemplate restTemplate;

    public int predict(PredictDTO predictDTO){
        // 准备请求参数
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("feature1", String.valueOf(predictDTO.getElectricity()));
        map.add("feature2", String.valueOf(predictDTO.getLine_loss()));
        map.add("feature3", String.valueOf(predictDTO.getWarn()));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);

        // 发起 POST 请求
        ResponseEntity<String> response = restTemplate.exchange(
                "http://127.0.0.1:5000/predict", // Flask 项目地址
                HttpMethod.POST,
                entity,
                String.class);

        // 处理返回结果
        if (response.getStatusCode() == HttpStatus.OK) {
            String predict_outcome = response.getBody();

            // 根据需要对预测结果进行后续处理
            predict_outcome.trim();//把字符串的空格去掉方便字符串转换成整数
            return Integer.parseInt( predict_outcome.trim()); // 假设预测结果是一个整数返回
        } else {
            // 处理请求失败的情况
            return -1;
        }
    }
}